import { getOssImgInfo } from "../api/ai"
import { getQiNiuAuthor } from "../api/login"

export function ossImage(path) {
	return new Promise((resolve, reject) => {
		getQiNiuAuthor().then(res => { //获取签名
			let token = res.data
			let date = new Date
			let year = date.getFullYear()
			let month = date.getMonth() + 1
			//获取文件后缀名
			var lastIndex = path .lastIndexOf('.');
			var extName = lastIndex > -1 ? path .slice(lastIndex + 1) : '';
			let stroeAs = "miniPro/" + year + "-" + month + "/" + Date.parse(new Date()) + parseInt(Math.random() * (100000 - 10000 + 1) + 10000, 10)+ "." + extName
			let host = "https://up-z2.qiniup.com"  //华南区
			let cdn = "https://sf01e0cvd.hn-bkt.clouddn.com" //这里用host拼接下载地址不能访问 暂时不知道为啥
			
			uni.uploadFile({
				url: host,
				filePath: path,
				name: 'file',
				formData: {
					'key': stroeAs,
					'token': token
				},
				success: (res) => {
					// console.log("上传成功", data.host + '/' + stroeAs)
					resolve(cdn + '/' + stroeAs)
				},
				fail: (err) => {
					console.log('上传失败', err);
					reject(err)
				}
			})

		}).catch(err => {
			reject(err)
		})
	})
}

export function ossImageAliYun(type, path) {
	return new Promise((resolve, reject) => {
		let id = 2
		getOssImgInfo({
			userId: id
		}).then(res => { //获取签名
			let data = res.data
			let date = new Date;
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let stroeAs = "bottle/" + year + "-" + month + "/" + Date.parse(new Date()) + parseInt(Math.random() * (100000 - 10000 + 1) + 10000, 10) + ".jpg"
			uni.uploadFile({
				url: data.host,
				filePath: path,
				name: 'file',
				formData: {
					'key': stroeAs,
					'policy': data.policyBase64,
					'OSSAccessKeyId': data.accessid,
					'signature': data.signature,
					'success_action_status': '200'
				},
				success: (res) => {
					console.log("上传成功", data.host + '/' + stroeAs)
					resolve(data.host + '/' + stroeAs)
				},
				fail: (err) => {
					console.log('上传失败', err);
					reject(err)
				}
			})

		}).catch(err => {
			reject(err)
		})
	})
}